package com.jyb.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jyb.vo.BaseVo;

public class ExceptionAndLogInterceptor implements Interceptor {

	private static Logger logger = Logger.getLogger(UserInterceptor.class);

	public void intercept(ActionInvocation ai) {

		Controller controller = ai.getController();
		HttpServletRequest request = controller.getRequest();
		try {
			ai.invoke();
		} catch (Exception e) {
			logger.error(e.toString());

			// 判断是否ajax请求
			String header = request.getHeader("X-Requested-With");
			boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
			String msg = formatException(e);
			if (isAjax) {
				BaseVo baseVo=new BaseVo();
				baseVo.setFlag(false);
				baseVo.setMsg(msg);
				controller.renderJson(baseVo);
			} else {
				controller.renderError(500);
			}

		} finally {
			
		}
	}

	/**
	 * 
	 * @param e
	 * @return
	 */
	private static String formatException(Exception e) {
		return e.toString();
	}

}
